<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2018/11/19
 * Time: 11:19
 */

namespace app\api\controller\v7;

use app\api\controller\v2\Auth;
use app\common\cachemodel\FortuneCache;
use app\common\lib\astrolog\FortunesChange;
use app\common\model\AppLogicVersion;
use app\common\model\SystemLogicVersion;
use app\common\model\AwardUser;
use app\common\model\Orders;
use app\common\model\Recode;
use Exception;
use think\Env;
use think\Log;
use think\response\Json;

class FortuneForMonth extends Auth
{
    protected $month_id;

    protected $active_switch;

    protected $msg;

    public function _initialize()
    {
        parent::_initialize();

        $this->month_id = config('goods.month_id');
        $this->active_switch = false;
//        $this->active_switch = checktime();
    }

    /**
     * 月运详情
     * @return Json
     * @throws Exception
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $uid = $this->user['id'];
        $rid = input('param.rid/d', 0);
        $year = input('param.year/d', 0);
        $month = input('param.month/d', 0);
        $this->check_param($rid, $year, $month);
        if ($this->msg)
        {
            Log::write('v7月运详情请求参数有误：' . $this->msg, 'notice', true);
            return show(config('code.error'), $this->msg);
        }
        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }
        //当前查看的时间
        $now_time = strtotime($year . '-' . $month);
        //日历显示时间范围
        $range_start = config('fortune.fortune_time_range')['month']['start'];
        $range_end = config('fortune.fortune_time_range')['month']['end'];


        $OrdersModel = new  Orders();
        $RecodeModel = new Recode();

        //解锁状态
        $unlock_status = 0;

        $unlock_data = FortuneCache::getUnlockFortune($this->user['id'], $rid, 3);
        switch (true)
        {
            case in_array($now_time, $unlock_data['computing_fortune']):
                $unlock_status = 1;
                break;
            case in_array($now_time, $unlock_data['completed_fortune']):
                $unlock_status = 2;
                break;
        }
        $time_range = array_map(function ($timeValue)
        {
            return date('Y-n', $timeValue);
        }, $unlock_data['unlock_fortune']);

        //统计订单人数
        $fortune_base_num = $OrdersModel->fortune_base(['type' => 1]);

        if ($unlock_status == 0)
        {
            $unlock_tips = [
                'title' => '月度报告解锁',
                'content' => '解锁当前运势,可查看你本月会发生什么,并提前七天得到预警,得知对应的方法和建议。',
            ];
        } elseif ($unlock_status == 1)
        {
            $unlock_tips = [
                'title' => '月度报告解锁等待中...',
                'content' => '由于月运的计算量较大,准了将在24小时内为您献上您所需要的月运。
小伙伴们耐心等待哦~',
            ];
        } elseif ($unlock_status == 3)
        {
            $unlock_tips = [
                'title' => '月度报告更新等待中...',
                'content' => '由于月运正在重新计算中,准了将在24小时内为您献上您所需要的月运。',
            ];
        } else
        {
            $unlock_tips = [];
        }

        //更新逻辑数据定义
        $update_logic = [
            'title' => '',
            'content' => '',
            'status' => 0
        ];
        //用户计算成功后获取运势信息并查询逻辑版本信息
        if ($unlock_status === 2)
        {
            $map = ['uid' => $uid, 'id' => $rid];
            //获取档案信息
            $recode_info = $RecodeModel->getRecode($map);

            //获取运势信息
            $fortune = (new FortunesChange())->init($recode_info, $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT));

            //获取当前最新版本逻辑信息
            $SystemLogicModel = new SystemLogicVersion();
            $logic_data = $SystemLogicModel->getVersion(['type' => 2]);
            //获取当前档案逻辑版本号
            $AppLogicModel = new AppLogicVersion();
            $user_logic = $AppLogicModel->getVersion(['rid' => $rid, 'type' => 2, 'time' => date('Y-m', $now_time)]);

            if ($user_logic)
            {
                //若查看的时间版本号不是最新,提示更新
                if ($logic_data['version'] && $user_logic < $logic_data['version'])
                {
                    $update_logic = [
                        'title' => $logic_data['title'],
                        'content' => $logic_data['content'],
                        'status' => 1,
                    ];
                }
            } elseif (!$user_logic)
            {
                $update_logic = [
                    'title' => $logic_data['title'],
                    'content' => $logic_data['content'],
                    'status' => 1,
                ];
            }
        } else
        {
            $fortune = [
                'underway_fortune' => [],
                'predicted_fortune' => [],
                'completed_fortune' => [],
            ];
        }

        $data = [
//            'self_rid' => (int)($recode_info['id']),
            'time' => $time_range,
            'underway_fortune' => $fortune['underway_fortune'],
            'predicted_fortune' => $fortune['predicted_fortune'],
            'completed_fortune' => $fortune['completed_fortune'],
            'unlock_num' => (int)($fortune_base_num),
            'unlock_status' => $unlock_status,
            'time_range' => [
                'start_time' => $range_start,
                'end_time' => $range_end,
            ],
            'update_logic' => $update_logic,
            'unlock_tips' => $unlock_tips,
        ];

        // 活动开关，默认关闭
        $config = config('active.fortune_active');

        $data['active_switch'] = [
            'day_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => '',
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ],
            'month_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ],
            'year_active' => [
                'is_open' => false,
                'icon' => $config['icon'],
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ]

        ];
        //若未解锁并在活动时间内，开启
        if ($this->active_switch)
        {
            $data['active_switch']['day_active']['is_open'] = false;
            $data['active_switch']['month_active']['is_open'] = true;
            $data['active_switch']['year_active']['is_open'] = true;
        }

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 检测运势首页请求参数
     * @param $rid
     * @param $year
     * @param $month
     * @return string
     */
    private function check_param($rid, $year, $month)
    {
        $this->msg = '';
        if (!$rid)
        {
            return $this->msg = '缺少档案';
        }
        if (!$year || !$month)
        {
            return $this->msg = '未知的时间';
        }
        if (!in_array($month, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true))
        {
            return $this->msg = '缺少月份';
        }
    }
}
